import io
import base64
import typing
import barcode
from PIL.Image import Image
from barcode.writer import ImageWriter


MY_OPTIONS: dict = {
    'module_width': 0.20,
    'module_height': 9.0,
    'quiet_zone': 0.5,
    'font_size': 0.1,
    'text_distance': 0.1,
    'background': 'white',
    'foreground': 'black',
    'write_text': False,
    'center_text': False,
    'text_line_distance': 0.1
}


class MyImage(ImageWriter):
    def __init__(self, dpi: int = 200, format: str = "PNG", mode: str = "RGB") -> None:
        super().__init__(format=format, mode=mode)
        self.dpi = dpi


def generate_img(code: str, option: typing.Dict[str, float | str] = MY_OPTIONS) -> Image:
    return barcode.Code128(code=code, writer=MyImage()).render(writer_options=option)


def return_bytes(img: Image, return_str: bool = True) -> str | bytes:
    bif = io.BytesIO()
    img.save(bif, format='PNG')
    ready_img = base64.b64encode(bif.getvalue())
    return ready_img.decode('utf-8') if return_str else base64.decodebytes(ready_img)
